// LoginServlet.java
package com.cdvtc.fengchao.Servlet;

import com.cdvtc.fengchao.dao.UsersDAO;
import com.cdvtc.fengchao.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 验证参数
        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
            request.setAttribute("error", "用户名或密码不能为空");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        // 查询数据库验证用户
        UsersDAO usersDAO = new UsersDAO();
        User user = usersDAO.getUserByUsernameAndPassword(username, password);

        if (user != null) {
            // 登录成功，将用户信息存入 session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            // 重定向到首页或其他页面
            response.sendRedirect("http://localhost:8080/fengchao_war_exploded/products");
        } else {
            // 登录失败，返回登录页面并显示错误信息
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}